package com.movisol.questionwizard.views;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.media.AudioManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

import com.movisol.c2dm.events.RegistrationIdReceivedEvent;
import com.movisol.c2dm.helpers.C2DMHelper;
import com.movisol.c2dm.ilisteners.IRegistrationIdReceived;
import com.movisol.questionwizard.applicationcontroller.ApplicationController;
import com.movisol.questionwizard.applicationcontroller.events.PushNotificationSubscribedEvent;
import com.movisol.questionwizard.applicationcontroller.listeners.IPushNotificationSubscribed;
import com.movisol.questionwizard.applicationcontroller.service.ProfileServiceManager;
import com.movisol.questionwizard.interfaces.ScreenViewable;
import com.movisol.questionwizard.views.asynctasks.AsyncSubscribePushNotification;
import com.movisol.tools.HelperUtils;

public class Splash extends Activity implements ScreenViewable, IRegistrationIdReceived, IPushNotificationSubscribed{

	private final static int SPLASH_LOADING_BOX_ORIGIN_TOP = 0;
	protected ApplicationController ac = ApplicationController.getInstance();
    private boolean finish=false;
    private Context context;
    private Activity activity = null;
  
	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	   super.onCreate(savedInstanceState);
   	       this.setVolumeControlStream(AudioManager.STREAM_MUSIC);  
    	   ac.setExit(true);
    	   activity = this;
    	   ac.setLastLanguageUsed(HelperUtils.getDeviceLanguage());
    	   context = ac.getContext();
    	   setContentView(R.layout.splash);
   	       initializeControls();
   	       //Hay que setear antes el PSM ya que si no, no funcionan los listeners a los que nos registramos justo despues
   	       ac.setPsm(new ProfileServiceManager(context));
   	       ac.c2dmc.addRegistrationListener(this);
	       ac.addPushNotificationSubscribedListener(this);
   	       new AsyncLoadRaw().execute();
   	      
    }
	
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		
		ac.setExit(false);
		//If loading is finished, then finish the activity 
		if (finish) finish();
		return false;
	}
	
	/* (non-Javadoc)
	 * @see android.app.Activity#onKeyDown(int, android.view.KeyEvent)
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		 if ((keyCode == KeyEvent.KEYCODE_BACK))
		 {
			 return false; 
		 }
		else
			return super.onKeyDown(keyCode, event);
	}
	
	private class AsyncLoadRaw extends AsyncTask<Void, Void, Void>{

	@Override
	protected Void doInBackground(Void... params) {
		//ac.setQuestionsResourcesId(HelperUtils.getRawResource("appconfig", context));
		ac.setCommonsLiteralsResourceId(HelperUtils.getRawResource("commonsliterals", context));
		ac.setLiteralsResourceId(HelperUtils.getRawResource("literals", context));
		ac.initializeLiterals();
		ac.initializeQuestions();

		return null;
	}

	@Override
	protected void onPostExecute(Void result) {
		super.onPostExecute(result);
		
		if (C2DMHelper.isRegistrationIdExpired(context))
			ac.getRegistrationId(activity);
		else
			finishLoading();
	  
	}
	
}
	
	private void finishLoading()
	{
		ProgressBar pb=(ProgressBar)findViewById(R.id.splasPgbLoad);
		pb.setVisibility(View.INVISIBLE);
		TextView tvLoaded= (TextView) findViewById(R.id.txtLoaded);
		tvLoaded.setText(getString(R.string.tap_to_continue));
		ac.setNeedAppToReboot(false);
		finish=true;
	}
	
	@Override
	protected void onPause() 
	{
		super.onPause();
		if(ac.getUsageClient() != null)
			ac.getUsageClient().pauseTracking();
		
		if(ac.isExit())
		{
			ac.setAppVisible(false);
			ac.saveSharedPreferences();
			
		}
	}

	@Override
	protected void onResume() 
	{
		super.onResume();
		ac.setExit(true);
		
		ac.setAppVisible(true);

		if(ac.getUsageClient() != null && ac.isScreenOn())
			ac.getUsageClient().resumeTracking();

	}

	@Override
	public void initializeControls() 
	{
		
		ImageView splash = (ImageView) findViewById(R.id.imageViewSplash);
   
		splash.setBackgroundResource(HelperUtils.getDrawableResource("splash", context));
   
		RelativeLayout rBottomLayout = (RelativeLayout) findViewById(R.id.splashBottomLayout);
		rBottomLayout.setBackgroundColor(Color.BLACK);
		rBottomLayout.setVisibility(View.VISIBLE);
		RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT);
   
		if(HelperUtils.getConfigParam("splashLoadingBoxOriginY", context) != null)
		{
			if(Integer.valueOf(HelperUtils.getConfigParam("splashLoadingBoxOriginY", context)) == SPLASH_LOADING_BOX_ORIGIN_TOP)
				params.addRule(RelativeLayout.ALIGN_PARENT_TOP);
			else
				params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
		}
		else
		{
			params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
		}
   
		rBottomLayout.setLayoutParams(params);
		
		TextView tvLoaded= (TextView) findViewById(R.id.txtLoaded);
		tvLoaded.setText(getString(R.string.loading));
	}
	
	@Override
	public void registrationIdReceived(RegistrationIdReceivedEvent evt) {
		
		if(evt.getRegistrationId() != null)
			if(HelperUtils.checkConnectivity(context))
				new AsyncSubscribePushNotification().execute(C2DMHelper.getRegistrationId(context));
			else
				finishLoading();
		else
			finishLoading();
	}

	@Override
	public void pushNotificationSubscribed(PushNotificationSubscribedEvent evt) {
		finishLoading();
		
	}

	
}
